package.cpath = "luaclib/?.so;3rd/lua-cjson/?.so;"
local skynet = require "skynet" 
local json  = require "cjson"
 

FRIENDS = {} 
local FRIENDS_room = {}  --房间room_type总人数 
local FRIENDS_room_id_max = {}  --房间id max 
 
local FRIENDS_KEY = {}  
FRIENDS_KEY.key = 'friends_msg_'      --俱乐部新增  
 

-- 得到我加入的 俱乐部
--fid  俱乐部id  
--name  俱乐部名称   
--uid  玩家id   
--flag  玩家标示  1为管理员 2为成员 3为申请还未批准成员  
function FRIENDS.get_uid(uid) 
    local sql = string.format("select a.*,b.url,b.uid as fid_uid,b.note,c.name as fid_uid_name,b.text as fid_text,b.club_type,c.head from  `friends` a left join fid b on b.fid=a.fid left join user c on c.uid=b.uid where a.flag in (1,2 ) and a.uid = %d ",tonumber(uid))
    local data = skynet.call("MG_SAVE", "lua", "mysql_get_all", sql ) 
    return data
end
  
--   得到 俱乐部 信息
--fid  俱乐部id  
--name  俱乐部名称  
--uid  玩家id  
--flag  玩家标示  1为管理员 2为成员 3为申请还未批准成员 4黑名单
function FRIENDS.get_fid_one(fid) 
    local sql = string.format("select * from  `friends` where flag in (1,2) and fid = %d ",tonumber(fid)) 
    local data = skynet.call("MG_SAVE", "lua", "mysql_get_one", sql ) 

    return data
end
function FRIENDS.get_fid_admin(fid) 
    local sql = string.format("select * from  `friends` where flag = 1 and fid = %d ",tonumber(fid))
    local data = skynet.call("MG_SAVE", "lua", "mysql_get_all", sql ) 
    return data
end
function FRIENDS.get_fid(fid) 
    local sql = string.format("select distinct uid  from  `friends` where flag in (1,2) and fid = %d ",tonumber(fid))

    local data = skynet.call("MG_SAVE", "lua", "mysql_get_all", sql ) 
    return data
end
-- 申请 加入 俱乐部
function FRIENDS.add(uid,fid)   
    local sql = string.format("select * from  `friends` where flag = 1 and fid = %d",tonumber(fid))
    local data = skynet.call("MG_SAVE", "lua", "mysql_get_one", sql ) 
    if data ~= false then
        local sql = string.format("select * from  `friends` where uid = %d  and fid = %d ",tonumber(uid),tonumber(fid))
        local qu = skynet.call("MG_SAVE", "lua", "mysql_get_one", sql ) 
        if qu == false then
            local date = os.date("%Y-%m-%d %H:%M:%S");
            local sql = string.format("insert into `friends` values (0,%d,3,'%s',%d,'%s') ",tonumber(uid),data.name,tonumber(fid),date)
            local rs = skynet.call("MG_SAVE", "lua", "mysql_insert", sql ) 
            return rs
        elseif qu.flag == 3 then
            return -2 
        end
        return -1
    end
    return 0
end

 --  
function FRIENDS.update(uid,fid ) 
    local date = os.date("%Y-%m-%d %H:%M:%S");
    local sql = string.format("update  `friends` set flag = 2,time='%s' where uid = %d  and fid = %d ",date,tonumber(uid),tonumber(fid))

    local rs = skynet.call("MG_SAVE", "lua", "mysql_update", sql ) 
end
 --  
function FRIENDS.del(uid,fid ) 
    local sql = string.format("delete from  `friends` where uid = %d  and fid = %d ",tonumber(uid),tonumber(fid))

    local rs = skynet.call("MG_SAVE", "lua", "mysql_update", sql ) 
end

 -- 获取俱乐部消息
function FRIENDS.get_msg(uid  )  
    local str = skynet.call("MG_SAVE", "lua", "redis_lrange", FRIENDS_KEY.key .. uid,0,20 ) 
    local data = {} 
    local arr = {} 
    local old_room_id = {} 
    local now_time = os.time() - 3600 * 2 --  个小时以上数据不处理
    if str ~= nil then
        -- print('===============get_msg==================',#str)
        local data_key = 1
        for k,v in pairs(str) do
            arr = json.decode(v) 
            if arr['time'] < now_time then 
                if k > 1 then   --删除过期数据 
                    local rs = skynet.call("MG_SAVE", "lua", "redis_ltrim", FRIENDS_KEY.key .. uid,0,k-2 ) 
                else  
                    local rs = skynet.call("MG_SAVE", "lua", "redis_del", FRIENDS_KEY.key .. uid ) 
                end
                break
            end 
            local room_id = tonumber(arr['room_id'])
            if old_room_id[room_id] == nil then 
                old_room_id[room_id] = 1
                data[data_key] = arr 
                data_key = data_key + 1
            end 
            -- for kk,vv in pairs(old_room_id) do
            --     print('=old_room_idold_room_idold_room_idold_room_idold_room_idold_room_idold_room_idold_room_id==================',kk)
            -- end
        end
    end
    return data
end

-- 增加俱乐部消息   房间消息  
--uid 创建者UID fid 要推送的俱乐部id room_id 要推送到的俱乐部id game_type 游戏类型
function FRIENDS.add_msg_room( uid,fid,data ) 
    data.time = os.time()
    data.uid = uid
    local str = json.encode(data)
    -- print('========'..str)
    local users = FRIENDS.get_fid(fid) 
    local to_uid
 
    if users ~= nil and users ~= false then
        for k,v in pairs(users) do 
            -- if uid ~= v['uid'] then --给房主自己发消息
                to_uid = v['uid'] 
                local rs = skynet.call("MG_SAVE", "lua", "redis_lpush", FRIENDS_KEY.key .. to_uid,str ) 
            -- end
        end
    end
end


function FRIENDS.friends_add(uid,fid) 
    local id = FRIENDS.add(tonumber(uid),tonumber(fid)) 


    return id
end
function FRIENDS.friends_get(uid)
    local  list = FRIENDS.get_uid(tonumber(uid) )  
    local new_list = {}
    if list == false then
        return false,nil
    end
    for k,v in pairs(list) do
        if v.url == nil then
            v.url = '' 
        end
        if v.note == nil then 
            v.note = ''
        end
        local is_flag = 0
        if v.fid_text ~= nil then  
            local text = {}
            if v.fid_text ~= '' then
                text = json.decode(v.fid_text)
                if text.blacklist ~= nil then
                    for ii,vv in pairs(text.blacklist) do
                        if vv == uid then
                            is_flag = 1 
                        end
                    end   
                end   
            end
        end 
        v.num = 0 
        local query_sql = string.format("select count(1) as num from friends where fid= %d and flag in (1,2)",v.fid)  
        local rsss = skynet.call("MG_SAVE","lua","mysql_get_one",query_sql)
        if rsss ~= false then   
            v.num = rsss.num 
        end 
        if is_flag == 0 then
            table.insert(new_list,v)
        end
    end
    return true,new_list
end

function FRIENDS.friends_msg(uid,fid) 
    local rs = {}      


    local text = nil  
    local room_club = {}  

    local query_sql = string.format("select * from fid where fid = %d",fid)  
    local rsss = skynet.call("MG_SAVE","lua","mysql_get_one",query_sql)   
    if rsss ~= false then 
        if rsss.text ~= nil and rsss.text ~= '' then 
            local text_arr = json.decode(rsss.text)  
            if text_arr ~= nil and text_arr.room_set ~= nil then  
                text = text_arr.room_set
            end
        end
    end

    if text == nil then 
        text = {}
        text.DOUNIU_HALL_0 = {room_odds=1,is_auto=1,hall_name="DOUNIU_HALL",optionType="111",gameType=130,ruleType=0,total_ju=20,fid=fid,autoSetID=0 }
        text.YFMJ_HALL_0 = {room_odds=1,is_auto=1,hall_name="YFMJ_HALL",optionType="1000",gameType=120,ruleType=0,total_ju=8,fid=fid,autoSetID=0}
    end

    local rooms = skynet.call("CLUB", "lua", "get_room",fid) 
    for i,v in pairs(rooms) do 
        room_id = v 
        local room_is_ok,hall_name,autoSetID,is_user,room_data  = get_room_info( room_id,rs,fid ) 
        if room_is_ok == 0 then 
            -- skynet.call("CLUB", "lua", "del_room",fid,room_id)
        else
            local is_del_del = 0
            if is_user == 0 then
                for i,v in pairs(text) do 
                    if  hall_name == v.hall_name and autoSetID == v.autoSetID and room_data.set_time ~= v.set_time then
                        is_del_del = 1
                    end  
                end  
            end  
            if is_del_del == 0 then
                local tmp_key = hall_name .. '_' .. autoSetID
                room_club[tmp_key] = 1
            else
                -- skynet.call("CLUB", "lua", "del_room",fid,room_id)
            end
        end  
    end  

    for i,v in pairs(text) do 
        if v.is_auto ~= nil and v.is_auto == 1 then
            local hall_name = v.hall_name 
            if v.autoSetID == nil then
                v.autoSetID = 0
            end
            local tmp_key = hall_name .. '_' .. v.autoSetID
            if room_club[tmp_key] == nil then
                local add_room_id = 0  
                while add_room_id == 0 do
                    add_room_id = skynet.call("MG_SAVE", "lua", "redis_addroom",0) 
                    local fd_old = skynet.call(hall_name, "lua", "get_rooms", add_room_id)
                    if fd_old ~= nil then
                        add_room_id = 0
                    end 
                end 
                skynet.call("MG_SAVE", "lua", "hall_name_hset", add_room_id, hall_name)
                v.room_id = add_room_id
                local id,fd = skynet.call(hall_name, "lua", "create_room", v)   
                get_room_info( add_room_id,rs,fid ) 
                skynet.call("CLUB", "lua", "add_room",fid,add_room_id)
            end 
        end
    end  
   
    return true,rs
end

function get_room_info( room_id,rs,fid )  
    local hall_name = skynet.call("MG_SAVE", "lua", "hall_name_hget", room_id) 
    local fd,room_data = skynet.call(hall_name, "lua", "get_rooms", room_id ) 
    -- print('hall_name========',hall_name)
    if fd == nil then
        skynet.call("CLUB", "lua", "del_room",fid,room_id)
    else
        if room_data['autoSetID'] == nil then
            room_data['autoSetID'] = 0
        end
        local info,room_info,is_one = skynet.call( fd, "lua", "get_users" )  
        if is_one > 0 then
            skynet.call("CLUB", "lua", "del_room",fid,room_id) 
        end
        if room_info ~= nil and is_one ~= nil then
            if room_info.friend_id == fid and is_one == 0 then
                room_is_ok = 1
                local id_key = 0 
                room_data['gameType'] = room_info['gameType'] 
                room_data['ruleType'] = room_info['ruleType'] 
                room_data['optionType'] = room_info['optionType'] 
                if room_info['player_num'] ~= nil then
                    room_data['player_num'] = room_info['player_num']  
                end
                if room_info['niao_num'] ~= nil then
                    room_data['niao_num'] = room_info['niao_num']  
                end
                room_data.users = {} 
                for kk,vv in pairs(info) do 
                    if vv ~= false and vv ~= nil then  
                        local user = {}
                        id_key = id_key + 1
                        user.name = vv['name']
                        user.head = vv['head'] 
                        room_data.users[id_key] = user
                    end
                end
                if (room_info['gameType'] == 130 or room_info['gameType'] == 131)  and id_key < 5 then  
                    table.insert(rs, room_data)
                    return 1,room_info['hall_name'],room_data['autoSetID'],id_key,room_data 
                end  
                if room_info['player_num'] ~= nil and id_key < room_info['player_num'] then  
                    table.insert(rs, room_data)
                    return 1,room_info['hall_name'],room_data['autoSetID'],id_key,room_data 
                end
            end
        end  
    end  
    return 0,'',0,0
end

--判断uid是否是 fid 的成员
function FRIENDS.is_uid_fid(uid,fid) 
    local sql = string.format("select * from  `friends` where uid = %d and fid = %d ",
            tonumber(uid),tonumber(fid)) 
    local data = skynet.call("MG_SAVE", "lua", "mysql_get_one", sql ) 
    local rs = 0
    if data ~= false and data['flag'] > 0 then
        rs = data['flag']
    end
    return rs  
end

function FRIENDS.is_fid_back_uid(uid,fid) 
    local query_sql = string.format("select fid,uid,text from fid where fid= %d ",fid)   
    local rsss = skynet.call("MG_SAVE", "lua", "mysql_get_one", query_sql ) 
    local rs = 0
    if rsss ~= false  then
        local text = {}
        if rsss.text ~= '' then
            text = json.decode(rsss.text)
        end
        if text.blacklist == nil then 
            text.blacklist = {}
        end
        for i,v in pairs(text.blacklist) do
            if v == uid then
                rs = 1
                break
            end
        end     
    end
    return rs  
end

--在 fid 删除由uid 创建的私房消息  
function FRIENDS.del_msg(uid,fid) 
    uid = tonumber(uid) 
    local users = FRIENDS.get_fid(fid) 
    local to_uid
    if users ~= nil then
        for k,v in pairs(users) do
            if uid ~= v['uid'] then
                to_uid = v['uid'] 
                --获取uid 的msg 
                local str = skynet.call("MG_SAVE", "lua", "redis_lrange", FRIENDS_KEY.key .. to_uid,0,20 ) 
                local arr = {} 
                local now_time = os.time() - 3600 * 2 --  个小时以上数据不处理
                if str ~= nil then
                    for k,vv in pairs(str) do
                        arr = json.decode(vv)
                        if arr['time'] < now_time then
                            if k > 1 then   --删除过期数据 
                                local rs = skynet.call("MG_SAVE", "lua", "redis_ltrim", FRIENDS_KEY.key .. uid,0,k-2 ) 
                            else 
                                local rs = skynet.call("MG_SAVE", "lua", "redis_del", FRIENDS_KEY.key .. uid ) 
                            end
                            break
                        end 
                        if arr['uid'] == uid then 
                            local rs = skynet.call("MG_SAVE", "lua", "redis_lrem", FRIENDS_KEY.key .. to_uid, 0, vv ) 
                            break 
                        end  
                    end
                end
            end
        end
    end
end

return FRIENDS
